package com.cpr.core.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author Chen Panrui
 * created at 2021/12/23 14:31
 *
 */
public class NioServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 1、打开一个通道 服务端的nio的Socket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8888));
        System.out.println("启动服务器...");
        // 3、设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        while (!Thread.currentThread().isInterrupted()){
            // 通道-channel-是基于缓存区Buffer的
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel == null){
                // 没有客户端连接-非阻塞的
                System.out.println("没有客户端连接...");
                TimeUnit.SECONDS.sleep(2);
                continue;
            }
            // 有连接-创建缓冲区-大小为1024字节
            ByteBuffer allocate = ByteBuffer.allocate(1024);
            // 本次连接读到的有效字节数，-1代表读到了末尾
            /*
             * 此时，客户端 和 服务端 建立了连接，如果client此时不发送数据，那么会在这里阻塞了(由于读写造成的阻塞-需要selector选择器去监听服务端channel的读写事件)
             */
            int read = socketChannel.read(allocate);
            System.out.println("客户端消息:" + new String(allocate.array(),0,read, StandardCharsets.UTF_8));
            socketChannel.write(ByteBuffer.wrap("没钱".getBytes(StandardCharsets.UTF_8)));
            // 释放
            socketChannel.close();
        }
    }
}
